import 'dart:async';

import 'package:bordered_text/bordered_text.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:dear_lottery/tools/DL_Config.dart';
import 'package:dear_lottery/tools/models/DL_DataViewModel.dart';
import 'package:dear_lottery/tools/models/DL_LottoModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../tools/FL_CustomLoading.dart';

// import '../../tools/KaL_Config.dart';

class DL_headerview_home extends StatefulWidget {
  const DL_headerview_home({super.key});

  @override
  State<DL_headerview_home> createState() => _DL_headerview_homeState();
}

class _DL_headerview_homeState extends State<DL_headerview_home> {
  ///倒计时定时器
  late Timer _timer;

  late var _timeDiffToNextDraw = 0; // 倒计时

  int _hours = 0;
  int _minutes = 0;
  int _seconds = 0;

  late var _nextDrawnModel = DL_NextDrawModel();

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    _nextDrawnModel = DL_DataViewModel().nextDrawnModel;
    _timeDiffToNextDraw = _nextDrawnModel.seconds_until_draw!;
    startCountdown();
    getNextDrawnData();
  }

  void startCountdown() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (mounted) {
        setState(() {
          if (_timeDiffToNextDraw > 0) {
            _timeDiffToNextDraw--;
          } else {
            timer.cancel();
            Future.delayed(const Duration(seconds: 2), () {
              getNextDrawnData();
            });
          }
        });
      }
    });
  }

  void formatTime(int seconds) {
    int hours = (_timeDiffToNextDraw ~/ 3600);
    int minutes = (_timeDiffToNextDraw % 3600) ~/ 60;
    int seconds = _timeDiffToNextDraw % 60;

    _hours = int.parse(hours.toString().padLeft(2, '0'));
    _minutes = int.parse(minutes.toString().padLeft(2, '0'));
    _seconds = int.parse(seconds.toString().padLeft(2, '0'));
  }

  void getNextDrawnData() async {
    // BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
    //   return FLCustomLoading(
    //     themeColor: DL_Config.DL_MainColor,
    //   );
    // });

    bool isfinish = await DL_DataViewModel().getNextDrawnData();
    if (isfinish) {
      _timer.cancel();
      // BotToast.closeAllLoading();
      _nextDrawnModel = DL_DataViewModel().nextDrawnModel;
      _timeDiffToNextDraw = _nextDrawnModel.seconds_until_draw!;
      startCountdown();
    }
  }

  void buyTicketButtonClick() async {
    debugPrint('BUY TICKETS');
    String configLink = _nextDrawnModel.link!;
    Uri _url = Uri.parse(configLink);
    if (configLink.isNotEmpty) {
      if (!await launchUrl(_url, mode: LaunchMode.externalApplication)) {
        throw Exception('Could not launch $_url');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    //时间戳转时分秒
    formatTime(_timeDiffToNextDraw);

    return Container(
      margin: const EdgeInsets.all(10),
      padding: const EdgeInsets.all(10),
      // height: 200,
      decoration: BoxDecoration(
        image: const DecorationImage(
          image: AssetImage('assets/sys_imgs/headerBG_Image.png'), // 替换为你的图片路径
          fit: BoxFit.cover, // 适应方式
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.2), // 阴影颜色
            spreadRadius: 1, // 扩散半径
            blurRadius: 10, // 模糊半径
            offset: const Offset(0, 1), // 阴影偏移
          ),
        ],
        borderRadius: const BorderRadius.all(Radius.circular(10)),
      ),
      child: Column(children: [
        Container(
          height: 25,
          padding: const EdgeInsets.fromLTRB(25, 3, 25, 3),
          decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.3),
              borderRadius: const BorderRadius.all(Radius.circular(25 * 0.5))),
          child: const Text(
            'NEXT DRAW',
            style: TextStyle(
                color: Colors.black, fontSize: 12, fontWeight: FontWeight.w500),
          ),
        ),
        const SizedBox(height: 5),
        BorderedText(
          strokeWidth: 5.0,
          strokeColor: DL_Config.DL_jackpottextColor_w,
          child: Text(
            _nextDrawnModel.lottery_name!,
            textAlign: TextAlign.center,
            style: TextStyle(
              color: DL_Config.DL_MainColor,
              fontSize: 36.0,
              fontWeight: FontWeight.w900,
              fontFamily: 'BarlowCondensedBold',
            ),
          ),
        ),
        Text(
          _nextDrawnModel.istTimeString!,
          style: TextStyle(
            height: 3,
            fontWeight: FontWeight.w900,
            fontSize: 16,
            color: HexColor('#ff3433'),
          ),
        ),
        const SizedBox(height: 10),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            timeView('HOURS', _hours.toString()),
            const SizedBox(width: 10),
            timeView('MINUTES', _minutes.toString()),
            const SizedBox(width: 10),
            timeView('SECONDS', _seconds.toString()),
          ],
        ),
        const SizedBox(height: 10),
        _nextDrawnModel.playable! ? playableButton() : SizedBox(),
      ]),
    );
  }

  Widget timeView(String typeStr, String timeStr) {
    return Column(
      children: [
        Container(
          alignment: Alignment.center,
          height: 50,
          width: 60,
          decoration: const BoxDecoration(
              color: Colors.black,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Text(
            timeStr,
            style: const TextStyle(
                fontWeight: FontWeight.w800, fontSize: 34, color: Colors.white),
          ),
        ),
        Text(
          typeStr,
          style: const TextStyle(color: Colors.black, fontSize: 14),
        ),
      ],
    );
  }

  //play按钮
  Widget playableButton() {
    double height = 45;
    return Container(
      height: height,
      width: 150,
      decoration: BoxDecoration(
        color: HexColor('#ff3433'),
        borderRadius: BorderRadius.all(Radius.circular(height * 0.5)),
      ),
      child: OutlinedButton(
        onPressed: () {
          buyTicketButtonClick();
        },
        style: ButtonStyle(
          side: WidgetStateProperty.all(
              const BorderSide(width: 2.0, color: Colors.white)),
        ),
        child: Text(
          _nextDrawnModel.playable_text!,
          // _nextDrawnModel.playable_text!,
          textAlign: TextAlign.center,
          style: const TextStyle(
              height: 1.1, //行间距
              fontSize: 15.0,
              color: Colors.white,
              fontWeight: FontWeight.w600),
        ),
      ),
    );
  }
}
